package com.lanzuo.pana.adapter.client.watcher;

import cn.hutool.core.util.StrUtil;
import com.jcraft.jsch.*;
import com.lanzuo.pana.adapter.exception.FileConnectionException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.net.ConnectException;

@Slf4j
@Getter
public class SshConnector {
    ChannelSftp sftpChannel;
    Session session;
    Channel channel;
    SshConfig config;
    LanzuoChannelSftp client;

    public SshConnector(SshConfig config) {
        this.config = config;
        this.connect();
    }

    public void connect() {
        // 1. 建立 SSH 连接
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
            session.setPassword(config.getPassword());

            // 不检查 HostKey（生产环境建议使用 known_hosts）
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            try {
                // 2. 打开 SFTP 通道
                channel = session.openChannel("sftp");
                channel.connect();
                sftpChannel = (ChannelSftp) channel;

                this.client = new LanzuoChannelSftp(session, sftpChannel, config);

            } catch (Exception e) {
                log.error("ssh文件夹连接异常， {}", e.getMessage());
                // 记录异常信息
                throw new ConnectException(e.getMessage());
            }
        } catch (JSchException | ConnectException e) {
            throw new FileConnectionException(StrUtil.format("ssh连接异常:{}", config.getHost()));
        }
    }

    public void disconnect() {
        if (sftpChannel != null) sftpChannel.disconnect();
        if (channel != null) channel.disconnect();
        if (session != null) session.disconnect();
    }


    public boolean isConnected() {
        return session != null && session.isConnected();
    }

}
